package com.xuecheng.content.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.sun.media.sound.FFT;
import com.xuecheng.base.exception.CommonError;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.base.model.PageParams;
import com.xuecheng.base.model.PageResult;
import com.xuecheng.content.mapper.*;
import com.xuecheng.content.model.dto.AddCourseDto;
import com.xuecheng.content.model.dto.CourseBaseInfoDto;
import com.xuecheng.content.model.dto.EditCourseDto;
import com.xuecheng.content.model.dto.QueryCourseParamsDto;
import com.xuecheng.content.model.po.*;
import com.xuecheng.content.service.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;


/**
 * @description 课程信息管理业务接口实现类
 * @author Mr.M
 * @date 2022/9/6 21:45
 * @version 1.0
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class CourseBaseInfoServiceImpl extends ServiceImpl<CourseBaseMapper,CourseBase> implements CourseBaseInfoService {
    private final CourseBaseMapper courseBaseMapper;



    private final CourseMarketService courseMarketService;



    private final CourseCategoryService courseCategoryService;

    private final CourseTeacherMapper courseTeacherMapper;

    private final TeachplanMapper teachplanMapper;



//

    @Override
    public PageResult<CourseBase> queryCourseBaseList(QueryCourseParamsDto queryCourseParamsDto) {
        String courseName = queryCourseParamsDto.getCourseName();
        String auditStatus = queryCourseParamsDto.getAuditStatus();
        String publishStatus = queryCourseParamsDto.getPublishStatus();

        Page<CourseBase> page = queryCourseParamsDto.toMpPageDefaultSortByUpdateTime();


        Page<CourseBase> p = lambdaQuery()
                .like(StringUtils.isNotEmpty(courseName), CourseBase::getName, courseName)
                .eq(StringUtils.isNotEmpty(auditStatus), CourseBase::getAuditStatus, auditStatus)
                .eq(StringUtils.isNotEmpty(publishStatus),CourseBase::getStatus,publishStatus)
                .page(page);

        PageResult<CourseBase> courseBasePageResult =  PageResult.of(p, CourseBase.class);

        return courseBasePageResult;

    }


//    @Override
//    public PageResult<CourseBase> queryCourseBaseList(PageParams pageParams, QueryCourseParamsDto queryCourseParamsDto) {
//
//
//        //构建查询条件对象
//        LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper<>();
//        //构建查询条件，根据课程名称查询
//        queryWrapper.like(StringUtils.isNotEmpty(queryCourseParamsDto.getCourseName()),CourseBase::getName,queryCourseParamsDto.getCourseName());
//        //构建查询条件，根据课程审核状态查询
//        queryWrapper.eq(StringUtils.isNotEmpty(queryCourseParamsDto.getAuditStatus()),CourseBase::getAuditStatus,queryCourseParamsDto.getAuditStatus());
////构建查询条件，根据课程发布状态查询
////todo:根据课程发布状态查询
//
//        //分页对象
//        Page<CourseBase> page = new Page<>(pageParams.getPageNo(), pageParams.getPageSize());
//        // 查询数据内容获得结果
//        Page<CourseBase> pageResult = courseBaseMapper.selectPage(page, queryWrapper);
//        // 获取数据列表
//        List<CourseBase> list = pageResult.getRecords();
//        // 获取数据总数
//        long total = pageResult.getTotal();
//        // 构建结果集
//        PageResult<CourseBase> courseBasePageResult = new PageResult<>(list, total, pageParams.getPageNo(), pageParams.getPageSize());
//        return courseBasePageResult;
//
//
//    }

    @Override
    @Transactional
    public CourseBaseInfoDto createCourseBase(Long companyId, AddCourseDto dto) {

        //合法性校验
        if (StringUtils.isBlank(dto.getName())) {
            throw new XueChengPlusException("课程名称为空");
        }

        if (StringUtils.isBlank(dto.getMt())) {
            throw new XueChengPlusException("课程分类为空");
        }

        if (StringUtils.isBlank(dto.getSt())) {
            throw new XueChengPlusException("课程分类为空");
        }

        if (StringUtils.isBlank(dto.getGrade())) {
            throw new XueChengPlusException("课程等级为空");
        }

        if (StringUtils.isBlank(dto.getTeachmode())) {
            throw new XueChengPlusException("教育模式为空");
        }

        if (StringUtils.isBlank(dto.getUsers())) {
            throw new XueChengPlusException("适应人群");
        }

        if (StringUtils.isBlank(dto.getCharge())) {
            throw new XueChengPlusException("收费规则为空");
        }

        //新增对象
        CourseBase courseBaseNew = BeanUtil.copyProperties(dto, CourseBase.class);

        //设置审核状态
        courseBaseNew.setAuditStatus("202002");
        //设置发布状态
        courseBaseNew.setStatus("203001");
        //机构id
        courseBaseNew.setCompanyId(companyId);
        //添加时间
        courseBaseNew.setCreateDate(LocalDateTime.now());
        //插入课程基本信息表
        int insert = courseBaseMapper.insert(courseBaseNew);
        if(insert<=0){
            throw new RuntimeException("新增课程基本信息失败");
        }

        //向课程营销表保存课程营销信息
        Long courseId = courseBaseNew.getId();
        CourseMarket courseMarketNew = BeanUtil.copyProperties(dto, CourseMarket.class);

        courseBaseNew.setId(courseId);

        if(!saveCourseMarket(courseMarketNew)){
            throw new RuntimeException("保存课程营销信息失败");
        }


        //查询课程基本信息及营销信息并返回
        return getCourseBaseInfo(courseId);

    }

    private boolean saveCourseMarket(CourseMarket courseMarketNew) {
        //收费规则
        String charge = courseMarketNew.getCharge();
        if(StringUtils.isBlank(charge)){
            throw new RuntimeException("收费规则没有选择");
        }
        //收费规则为收费
        if(charge.equals("201001")){
            if(courseMarketNew.getPrice() == null || courseMarketNew.getPrice().floatValue()<=0){
                throw new XueChengPlusException("课程的价格不能为空并且必须大于0");
            }
        }

        //判断是否已经存在
        //CourseMarket courseMarket = courseMarketMapper.selectById(courseMarketNew.getId());
//        boolean b = courseMarketService.saveOrUpdate(courseMarketNew);

        return courseMarketService.saveOrUpdate(courseMarketNew);

    }

    public CourseBaseInfoDto getCourseBaseInfo(long courseId) {
        CourseBase courseBase = getById(courseId);

        if (courseBase==null){
            return null;
        }

        CourseMarket courseMarket = courseMarketService.getById(courseId);
        CourseBaseInfoDto courseBaseInfoDto = BeanUtil.copyProperties(courseBase, CourseBaseInfoDto.class);


        if (courseMarket!=null){
            BeanUtil.copyProperties(courseMarket,courseBaseInfoDto);
        }

        //查询分类名称
        CourseCategory courseCategoryBySt = courseCategoryService.getById(courseBase.getSt());
        courseBaseInfoDto.setStName(courseCategoryBySt.getName());
        CourseCategory courseCategoryByMt = courseCategoryService.getById(courseBase.getMt());
        courseBaseInfoDto.setMtName(courseCategoryByMt.getName());

        return courseBaseInfoDto;
    }


    @Override
    public CourseBaseInfoDto updateCourseBase(Long companyId, EditCourseDto dto) {
        //课程id
        Long courseId = dto.getId();

        CourseBase courseBase = getById(courseId);

        if (courseBase==null){
            XueChengPlusException.cast("课程不存在");
        }

        //校验本机构只能修改本机构的课程
        if(!courseBase.getCompanyId().equals(companyId)){
            XueChengPlusException.cast(CommonError.COMPANY_ERROR);
        }

        //封装基本信息的数据
        BeanUtil.copyProperties(dto,courseBase);
        courseBase.setChangeDate(LocalDateTime.now());

        //更新课程基本信息
        updateById(courseBase);

        //封装营销信息的数据
        CourseMarket courseMarket = new CourseMarket();
        BeanUtils.copyProperties(dto,courseMarket);
        saveCourseMarket(courseMarket);
        //查询课程信息                      //todo  为何要用this
        CourseBaseInfoDto courseBaseInfo = this.getCourseBaseInfo(courseId);
        return courseBaseInfo;


    }

    @Override
    @Transactional
    public void deleteCourse(Long id, Long companyId) {
        CourseBase courseBase = getById(id);
        if (!courseBase.getCompanyId().equals(companyId)){
            XueChengPlusException.cast(CommonError.COMPANY_ERROR);
        }

        //课程的审核状态为未提交时方可删除。
        if (!courseBase.getAuditStatus().equals("202002")){
            XueChengPlusException.cast("审核状态不为未提交，不可删除");
        }
        //TODO 可以在这里加上非空判断，以判断是否删除成功
        //删除基本信息
        removeById(id);

        //删除课程营销信息
        courseMarketService.removeById(id);

        //删除课程计划
        teachplanMapper.delete(new LambdaQueryWrapper<Teachplan>()
                .eq(Teachplan::getCourseId, id));

        //删除课程教师信息
        courseTeacherMapper.delete(new LambdaQueryWrapper<CourseTeacher>()
                .eq(CourseTeacher::getCourseId,id));
    }
}
